import os

import yt_dlp
from moviepy import VideoFileClip

from dao import VideoDaoInstance,Video
from ytdlp_download.config import getDownloadOptions,get_video_path,get_poster_path




def download_file(url: str,name: str):
    print("downloading", name)
    options = getDownloadOptions(name)
    # return
    video_path = os.path.join(get_video_path(), name + ".mp4")
    info: Video = {
        "name": name,
        "url": url,
        "status": 1,
        "storepath": video_path,
    }
    try:
        with yt_dlp.YoutubeDL(options) as ydl:
            VideoDaoInstance.insertVideo(info)
            print(info)
            ydl.download([url])
            print(f"{name}:下载完成！,url:{url}")
            info["status"] = 2
            VideoDaoInstance.updateVideoByName(info)

    except Exception as e:
        info["status"] = 3
        VideoDaoInstance.updateVideoByName(info)
        print(f"{name}:发生错误: {e}")
    if info["status"] == 2:
        create_poster(name, video_path)



def create_poster(name:str,target_path:str):
    try:
        video = VideoFileClip(target_path)
        duration = video.duration
        frame_time = min(1.0, duration)
        save_path = os.path.join(get_poster_path(), f"{name}.jpg")
        video.save_frame(save_path,frame_time)
        video.close()
        print(f"给{target_path}生成poster成功")
    except Exception as e:
        print(f"给{target_path}生成poster失败,error:{e}")








